package com.cslg.controller;

import com.alibaba.fastjson.JSON;
import com.cslg.pojo.Uploadfile;
import com.cslg.pojo.User;
import com.cslg.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class UploadController {
    @Autowired
    private UploadService uploadService;
    @RequestMapping("/upload.do")
    @ResponseBody
    public String uploadFile(MultipartFile file, HttpSession session){
        String fileName = file.getOriginalFilename();
        System.out.println("上传文件的名称："+fileName);
        //将得到的文件保存到本地，可以用 IO 流，也可以使用第三方插件
        //指定文件存放的路径
        String path = "D:\\upload";
        //判断是否存在文件夹，若不存在则先创建出来
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdir();
        }
        //解决文件重名的问题：获取当前的时间戳，再加上6位的随机数
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+(new Random().nextInt(899999)+100000)+"-"+fileName;
        Map<String,Object> map = new HashMap<>();
        if (file!=null && !file.isEmpty()){ //说明文件不为空
            try {
                file.transferTo(new File(path+"\\"+newFileName));
                User user = (User)session.getAttribute("user");
                if (user!=null){
                    Uploadfile uploadFile = new Uploadfile();
                    uploadFile.setFilename(newFileName);
                    uploadFile.setUserid(user.getId());
                    uploadFile.setUploaddate(new Date());
                    //将文件名字保存到数据库中
                    int i = uploadService.insertFile(uploadFile);
                    if (i>0){
                        map.put("code", 200);
                        System.out.println("文件上传成功！");
                    }else {
                        map.put("code", 500);
                        System.out.println("文件上传失败！");
                    }
                }
            }catch (Exception e){
                System.out.println("文件上传失败！");
                map.put("code", 500);
                e.printStackTrace();
            }
        }
        //返回数据给前端
        map.put("msg", "");
        map.put("data", newFileName);
        //构建json数据
        String json = JSON.toJSONString(map);
        return json;
    }
}
